import logging
import time
from itertools import izip, repeat
from math import exp, log

import model
import pygooglechart as pgc

SECS_IN_DAY = 24*3600
CAFFEINE_HALF_LIFE = 5*3600

def intake_points(intake, start, end, increment):
    n0 = intake.caffeine_amount
    ts = intake.timestamp
    tindex = start
    while tindex < end:
        if tindex >= ts:
            y = n0 * exp(-(tindex-ts) * log(2) / CAFFEINE_HALF_LIFE)
            yield y
        else:
            yield 0
        tindex += increment

def y_data(user):
    start = time.time() - SECS_IN_DAY
    req = model.Intake.gql(
        'WHERE timestamp > :1 AND user = :2 ORDER BY timestamp DESC',
        start, user)
    intakes = [intake_points(i, start, start + 2*SECS_IN_DAY, 1200) for i in req]
    logging.info("Computing graph with %d intakes" % len(intakes))
    if len(intakes) == 0:
        return None

    results = []
    for x in izip(*intakes):
        logging.info(x)
        results.append(sum(x))
    return results

def graph_url(user):
    chart = pgc.XYLineChart(600, 300, x_range=(-SECS_IN_DAY, SECS_IN_DAY))
    data = y_data(user)
    if not data:
        return None

    data = list(data)
    high = max(data)

    chart.add_data(range(-SECS_IN_DAY, SECS_IN_DAY, 1200))
    chart.add_data(data)
    chart.add_fill_simple('FF9933')
    chart.set_colours(['CC6600'])
    chart.set_title('Bloodstream caffeine levels')
    chart.set_grid(12.5, 25, 1, 5)
    chart.set_axis_labels(pgc.Axis.BOTTOM, ['1 day ago',
                                            '12 hours ago',
                                            'now',
                                            'in 12 hours',
                                            'in 24 hours'])
    chart.set_axis_range(pgc.Axis.LEFT, 0, max(data))
    chart.set_axis_labels(pgc.Axis.LEFT, ['', '(mg)', ''])
    return chart.get_url()
